<?php
namespace app\index\model;
class Signcheck{
    private $keys="";
    /**
     * 生成签名
     * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
     */
    public function MakeSign($data)
    {
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string = $this->ToUrlParams($data);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=".$this->keys;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }
    public function setKey($key){
        $this->keys=$key;
    }
    /**
     * 格式化参数格式化成url参数
     */
    public function ToUrlParams($data)
    {
        $buff = "";
        foreach ($data as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }
    
        $buff = trim($buff, "&");
        return $buff;
    }
    public function checkSign($data){
        $res = $this->MakeSign($data);
        if ($data['sign']==$res){
            return true;
        }
        return false;
    }
    function paySuccess($needSign=false){
        $data['return_code']="SUCCESS";
        $data['return_msg']="OK";
        if ($needSign){
            $data['sign']=$this->MakeSign($data);
        }
        return $this->ToXml($data);
    }
    /**
     * 输出xml字符
     * @throws WxPayException
     **/
    public function ToXml($data)
    {
        $xml = "<xml>";
        foreach ($data as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }
}